from django.shortcuts import render, redirect
from accounts.forms import UserProfileForm
from accounts import models
import os
from django.conf import settings  # 导入Django的settings


import time

def save_user_avatar(avatar_file, user_id):
    try:
        # 构建保存目录：MEDIA_ROOT/img/users/<user_id>/avatar/
        avatar_dir = os.path.join(
            settings.MEDIA_ROOT,
            'img',
            'users',
            f'{user_id}',
            'avatar'
        )
        os.makedirs(avatar_dir, exist_ok=True)  # 确保目录存在

        # 固定文件名：avatar.jpg（覆盖旧文件）
        avatar_path = os.path.join(avatar_dir, 'avatar.jpg')

        # 先删除旧文件（确保完全覆盖）
        if os.path.exists(avatar_path):
            os.remove(avatar_path)

        # 写入新文件
        with open(avatar_path, 'wb+') as destination:
            for chunk in avatar_file.chunks():
                destination.write(chunk)

        # 返回相对路径
        relative_path = os.path.join('img', 'users', f'{user_id}', 'avatar', 'avatar.jpg')
        return True, "头像保存成功", relative_path
    except Exception as e:
        return False, str(e), None


def user_profile(request):
    user = request.user.regularuser  # 假设用户模型有OneToOne链接到RegularUser
    form = UserProfileForm(instance=user)

    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance=user)
        if form.is_valid():
            form.save()

    return render(request, 'user/profile.html', {'form': form, 'user': user})


def edit_user_profile(request, nid):
    if request.method == "GET":
        user = models.RegularUser.objects.filter(id=nid).first()
        return render(request, 'user/edit_profile.html', {'user': user, 'interest_choices': user.INTEREST_CHOICES})

    update_fields = {
        'nickname': request.POST.get('nickname'),
        'gender': request.POST.get('gender'),
        'birth_date': request.POST.get('birth_date') or None,
        'province': request.POST.get('province'),
        'city': request.POST.get('city'),
        'district': request.POST.get('district'),
        'interests': ','.join(request.POST.getlist('interests')) if request.POST.getlist('interests') else None,
        'travel_frequency': request.POST.get('travel_frequency', 0),
        'budget_preference': request.POST.get('budget_preference'),
        'wechat_id': request.POST.get('wechat_id'),
        'bio': request.POST.get('bio')
    }

    models.RegularUser.objects.filter(id=nid).update(**update_fields)

    avatar_file = request.FILES.get('avatar')
    if avatar_file:
        try:
            # 调用保存函数
            success, message, avatar_path = save_user_avatar(
                avatar_file=avatar_file,
                user_id=nid
            )

            if success:
                # 强制浏览器不使用缓存（添加时间戳参数）
                timestamp = int(time.time())
                avatar_url_with_timestamp = f"{avatar_path}?v={timestamp}"

                # 更新头像路径到数据库
                models.RegularUser.objects.filter(id=nid).update(avatar=avatar_url_with_timestamp)
            else:
                print(f"头像保存失败: {message}")
        except Exception as e:
            print(f"处理头像时出错: {str(e)}")

    return redirect('/homepage/')
